<template>
  <n-grid cols="1 s:1 m:1 l:4 xl:4 2xl:4" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formParams" :rules="rules" ref="formRef">
        <n-form-item label="APPID" path="gzhappid">
          <n-input v-model:value="formParams.gzhappid" placeholder="请输入APPID" />
        </n-form-item>

        <n-form-item label="AppSecret" path="gzhappsecret">
          <n-input v-model:value="formParams.gzhappsecret" placeholder="请输入AppSecret" />
        </n-form-item>

        <n-form-item label="公众号关注链接" path="gzh_url">
          <n-input type="textarea" 
          :autosize="{
            minRows: 3,
          }" 
          v-model:value="formParams.gzh_url" placeholder="请输入公众号关注链接" />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" :loading="subLoading" @click="formSubmit">更新公众号信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import { webconfigEdit,webconfiginfo } from '@/api/webconfig/index';
  
  const rules: FormRules = {
    gzhappid: {
      required: true,
      message: '请输入APPID',
      trigger: 'blur',
    },
    gzhappsecret: {
      required: true,
      message: '请输入AppSecret',
      trigger: 'input',
    },
    gzh_url: {
      required: true,
      message: '请输入公众号链接',
      trigger: 'input',
    },
  };

  const defaultValueRef = () => ({
    gzhappid: '',
    gzhappsecret: '',
    gzh_url: '',
  });

  const message = useMessage();
  const formRef: any = ref(null);
  const subLoading = ref(false);
  const formParams = ref(defaultValueRef());

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        webconfigEdit(formParams.value).then((_) => {
          message.success('更新成功');
        });
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  function getInfo() {
    webconfiginfo({}).then((res) => {
      const params = {
        gzhappid: res.gzhappid,
        gzhappsecret: res.gzhappsecret,
        gzh_url: res.gzh_url,
      };
      formParams.value = Object.assign(formParams.value, params);
    });
  }

  onMounted(async () => {
    getInfo();
  });
</script>
